//
//  composeViewController.swift
//  Weibo
//
//  Created by 明丽 on 16/1/23.
//  Copyright © 2016年 明丽. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
class composeViewController: UIViewController {
    @objc private func colse (){
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    @objc private func send() {
        print("我是发送")
        var urlSting = "https://api.weibo.com/2/statuses/update.json"
        let parameters = ["access_token": UserAccountViewController().token,"status":textView.text]
        if pictureSelectorVC.imageList.count != 0 {
            //图片转为2进制
            let imageData = UIImagePNGRepresentation(pictureSelectorVC.imageList.first!)!
            
            
        //上传图片的借口
            urlSting = "https://upload.api.weibo.com/2/statuses/upload.json"
            let afn = AFHTTPSessionManager()
            afn.POST(urlSting, parameters: parameters, constructingBodyWithBlock: { (fromData) -> Void in
                fromData.appendPartWithFileData(imageData, name: "pic", fileName: "x0", mimeType: "image/jpeg")
                
                }, progress: nil, success: { (_, result) -> Void in
                    print("输入成功")
                    SVProgressHUD.showSuccessWithStatus("发布成功", maskType: .Gradient)
                    self.dismissViewControllerAnimated(true, completion: nil)
                    
                }, failure: { (_, error) -> Void in
                    print("error")
            })
        
            
            
        }else{
        
            let af = AFHTTPSessionManager()
            af.POST(urlSting, parameters: parameters, progress: nil, success: { (_, rect) -> Void in
                SVProgressHUD.showSuccessWithStatus("发布成功")
                
                }) { (_, error) -> Void in
                    SVProgressHUD.showErrorWithStatus(AppErrorTip)
            }

        }
        
        
        
        
    }
    
    @objc private func selectPicture() {
        print("我是选择图片")
        //更新约束
        pictureSelectorVC.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(KHeight/3*2)
        }
        //用户体验更好动画效果
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
        
    }
    @objc private func selectEmoticon() {
        print("我是自定义表情")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()
        selectTime()
        //设置导航栏
        setNavBar()
        setTextView()
        setToolBar()
        registerNotification()
    }
    @objc private func keyBoardChange(n: NSNotification) {
        //获取动画时间
        let duation = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        let endRect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        let offsetY = -KHeight + endRect.origin.y
        UIView.animateWithDuration(duation) { () -> Void in
            //修改底部约束
            self.toolBar.snp_updateConstraints(closure: { (make) -> Void in
                make.bottom.equalTo(self.view.snp_bottom).offset(offsetY)
            })
            
            //强制刷新
            self.view.layoutIfNeeded()
        }
        
        
        
    }
    
    
    
    
    //注册键盘的监听事件
    private func registerNotification() {
        //注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        
    }
    //移除监听
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
        
    }
    
    
    
    
    
    //懒加载视图
    private lazy var textView: UITextView = {
        let tv = UITextView()
        // tv.text = "输入新鲜事"
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.darkGrayColor()
        tv.backgroundColor = UIColor.yellowColor()
        //开启弹簧效果
        tv.alwaysBounceVertical = true
        //关闭键盘
        tv.keyboardDismissMode = .OnDrag
        tv.delegate = self
        return tv
    }()
    //占位符
    private lazy var placeHolderLabel: UILabel = UILabel(title: "输入新鲜事", fontSize: 18, color: UIColor.lightGrayColor())
    
    //工具条
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    //懒加在图片
    private lazy var pictureSelectorVC : pictureSelectorViewController = pictureSelectorViewController()
    
    
}




extension composeViewController: UITextViewDelegate{
    
    func textViewDidChange(textView: UITextView) {
        //隐藏站位文本,如果有文本就隐藏文字
        placeHolderLabel.hidden = textView.hasText()
        //开始 右导航按钮的交互
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
}
extension composeViewController{
    
    //添加图片选择器
    private func selectTime() {
        addChildViewController(pictureSelectorVC)
        //添加控制器的视图
        view.addSubview(pictureSelectorVC.view)
        //设置约束
        pictureSelectorVC.view.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(0)
        }
        
        
    }
    
    
    private func setToolBar() {
        self.view.addSubview(toolBar)
        //设置约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.left.right.equalTo(self.view)
        }
        
        //添加toolbar的子视图
        var items = [UIBarButtonItem]()
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_add_background"]]
        
        for item in itemSettings {
            //获取图片名称
            let imageName = item["imageName"]
            let btn = UIButton(imageName: imageName, backImageName: nil)
            if let actionName = item["actionName"] {
                //添加点击事件
                btn.addTarget(self, action:Selector(actionName), forControlEvents: .TouchUpInside)
            }
            
            let item = UIBarButtonItem(customView: btn)
            //添加到数组里去
            items.append(item)
            //添加弹簧效果
            let apace = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil )
            items.append(apace)
        }
        //移除最后一个
        items.removeLast()
        toolBar.items = items
    }
    //输入的文字
    private func setTextView(){
        view.addSubview(textView)
        //设置约束
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.view.snp_top)
            make.left.right.equalTo(self.view)
            make.height.equalTo(KHeight/3)
            
        }
        //添加站位文本
        textView.addSubview(placeHolderLabel)
        //设置占位文本的约束
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
        
    }
    
    
    
    private func setNavBar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "colse")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "send")
        //禁用发送按钮
        navigationItem.rightBarButtonItem?.enabled = false
        
        //        //添加view
        let MyView = UIView(frame:CGRect(x: 0, y: 0, width: 200, height: 44))
        //添加子控制件
        let titleLable = UILabel(title: "发布微博", fontSize: 17, color: UIColor.redColor())
        MyView.addSubview(titleLable)
        //名字
        let titleName = UILabel(title: UserAccountViewController().userName ?? "", fontSize: 14, color: UIColor.blackColor())
        MyView.addSubview(titleName)
        
        //添加自动布局
        titleLable.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(MyView.snp_centerX)
            make.top.equalTo(MyView.snp_top)
        }
        titleName.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(MyView.snp_centerX)
            make.bottom.equalTo(MyView.snp_bottom)
        }
        navigationItem.titleView = MyView
    }
    
    
    
}
